<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use app\validate\CheckTopicType;
use think\exception\ValidateException;
use EasyWeChat\Factory;


// 话题分类
class TopicType extends BaseController
{

    public function index()
    {
        return View::fetch();
    }


    public function load(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];
        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['name|e_name', 'like', '%'.$get['key'].'%'];
            }
        }


        if (isset($get['field']) && isset($get['order'])) {
            if (!empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
            } else {
                $field = 'sort';
                $sort = 'asc';
            }
        } else {
            $field = 'sort';
            $sort = 'asc';
        }


        $total = Db::table('o_topic_type')
            ->where($where)
            ->count();


        $rows = Db::table('o_topic_type')
            ->where($where)
            ->field('id, sort, name, e_name')
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $topic_total = Db::table('o_topic')->whereFindInSet('type', $v['id'])->count();
            $hot_total = Db::table('o_topic')->whereFindInSet('type', $v['id'])->sum('hot');
            $v['topic_total'] = $topic_total;
            $v['hot_total'] = floor($hot_total);
        }

        $rows = sort_array($rows,$field,$sort);

        $limit = 10;

        $pages = $get['page'];
        if(empty($pages) || $pages==1){
            $Pages = 0;
        }else{
            $Pages = ($pages-1)*$limit;
        }

        $rows = array_slice($rows,$Pages,$limit);

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }



    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        return View::fetch();
    }

    //+banner保存
    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        // 验证
        try {

            validate(CheckTopicType::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $data = array(
                'name'          => $post['name'],
                'e_name'        => $post['e_name'],
                'role'          => $post['role'],
                'status'        => 1,
                'sort'          => 999,
                'add_time'      => time(),
                'update_time'   => time(),
            );
            if (!Db::name('topic_type')->insert($data)) {
                return $this->outputAjax('保存失败！');
            }
            return $this->outputAjax('保存成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
     * 修改
     */
    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');

        $inf = Db::name('topic_type')->find($id);

        View::assign('inf',$inf);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $this->request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckTopicType::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $update = array(
                'id'            => $post['id'],
                'name'          => $post['name'],
                'e_name'        => $post['e_name'],
                'role'          => $post['role'],
                'update_time'   => time(),
            );

            if (!Db::name('topic_type')->update($update)) {
                return $this->outputAjax('保存失败！');
            }
            return $this->outputAjax('保存成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }


    //+话题分类删除
    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        try {
            $where = array(
                'id' => $id
            );

            //+话题分类基本信息
            $inf = Db::name('topic_type')->where($where)->find();

            if (!$inf) {
                return $this->outputAjax('参数错误！');
            }

            if (!Db::name('topic_type')->where($where)->update(['status' => 3])) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+排序
    public function sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        if(empty($post)){
            return json(['code'=>'500','msg'=>'参数不足！','data'=>[]]);
        }

        if ($post['id'] == 33) {
            return $this->outputAjax('该分类不可修改排序！');
        }

        try {
            $res = Db::name('topic_type')->where('id', '=', $post['id'])->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }

            if (!is_numeric($post['sort'])) {
                return $this->outputAjax('请填写数字！');
            }

            if ($post['sort'] < 1 || $post['sort'] > 999) {
                return $this->outputAjax('排序数字在1-999之间！');
            }

            $rows = Db::name('topic_type')->where('id', '<>', $post['id'])->where('sort', '>=', $post['sort'])->order('sort asc')->select()->toArray();

            if (!Db::name('topic_type')->where(array('id'=>$post['id']))->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('topic_type')->where('id', '=', $post['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function getQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/MomentsBox/pages/topicInfo/topicInfo';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 300,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);
            return $this->outputAjax('获取成功', 0, ['url' => $qr]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function export(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();
        $where = [];
        if (!empty($get['key'])) {
            $where[] = ['c.name|c.e_name', 'like', '%'.$get['key'].'%'];
        }

        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '话题分类数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['话题名称', '订阅人carolid', '姓名', 'Division', '部门', '职位']);

        $total = Db::table('o_subscribe')
            ->alias('a')
            ->field('c.name as title, b.userid, b.name, b.division, b.department_name, b.position')
            ->join('o_members b','a.uid = b.id')
            ->join('o_topic_type c','a.aid = c.id')
            ->where($where)
            ->count();

        $nums = 1000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::table('o_subscribe')
                ->alias('a')
                ->field('c.name as title, b.userid, b.name, b.division, b.department_name, b.position')
                ->join('o_members b','a.uid = b.id')
                ->join('o_topic_type c','a.aid = c.id')
                ->where($where)
                ->limit($start, $nums)
                ->order('a.aid desc')
                ->select()
                ->toArray();

            foreach ($rows as &$value) {
                if(!$value['userid']) {
                    continue;
                } else {
                    $count = mb_strlen($value['userid']);
                    if ($count == 6) {
                        if (is_numeric($value['userid'])) {
                            $userid = "'00".$value['userid'];
                        } else {
                            $userid = $value['userid'];
                        }
                    } else {
                        $userid = $value['userid'];
                    }

                    $arr = [
                        $value['title'],
                        $userid,
                        $value['name'],
                        $value['division'],
                        $value['department_name'],
                        $value['position'],
                    ];
                    fputcsv($fp, $arr);
                }
            }
            //每1千条数据就刷新缓冲区
            flush();
        }
    }
}